//
//  RootWebViewController.m
//  YouYiKuProject
//
//  Created by xue on 2018/11/29.
//  Copyright © 2018年 xuezi. All rights reserved.
//

#import "RootWebViewController.h"
#import "GCWebviewJSBridge.h"
#import "HXPhotoPicker.h"
#import "WXApiRequestHandler.h"
#import "WXApiManager.h"
#import "WechatAuthSDK.h"
#import "UIAlertView+WX.h"
#import "APOrderInfo.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APRSASigner.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "WxPayModel.h"
#import <AVFoundation/AVFoundation.h>
#import "WXVoiceSDK.h"
#import "WXSpeechRecognizerViewController.h"
#import "WXApi.h"
#import "WXAuth.h"
#import "WXSpeech.h"
@interface RootWebViewController ()<UIWebViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,HXCustomCameraViewControllerDelegate,HXAlbumListViewControllerDelegate,WXApiManagerDelegate,UITextViewDelegate, WechatAuthAPIDelegate,WXVoiceDelegate,WXApiDelegate,WXAuthDelegate>
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) GCWebviewJSBridge *bridge;
@property (strong, nonatomic) HXPhotoManager *manager;

@property (strong, nonatomic) UILabel *msgLabel;
@property (strong, nonatomic) UIImageView *imageView;

@end

@implementation RootWebViewController

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.openCamera = NO;
        _manager.configuration.saveSystemAblum = NO;
        _manager.configuration.photoMaxNum = 1;
        _manager.configuration.maxNum = 1;
        _manager.configuration.reverseDate = NO;
        _manager.configuration.videoMaxDuration = 500.f;
        _manager.configuration.saveSystemAblum = YES;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.showDateSectionHeader = YES;
        _manager.configuration.selectTogether = NO;
        _manager.configuration.rowCount = 4;
        _manager.configuration.photoCanEdit =NO;

    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 1.新建WebView
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.webView];
    
    // 2.加载网页
//    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index1" ofType:@"html"];
//    NSString * htmlString = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]];
//    [self.webView loadHTMLString:htmlString baseURL:baseURL];

    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"default/index.html" relativeToURL:[[NSBundle mainBundle] bundleURL]]]];
    

    
    // 3.开启日志
    [GCWebviewJSBridge setEnableLogging];
    
    // 4.给webView建立JS和OC的沟通桥梁
    _bridge = [GCWebviewJSBridge bridgeForWebView:self.webView];
    [_bridge setwebViewDelegate:self];
    
    
    /* JS调用OC的API:访问相册 */
    [_bridge registerObjCHandler:@"openCamera" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        NSLog(@"需要%@图片", data[@"count"]);
        [self getPicImageList];
    }];
    
    [_bridge registerObjCHandler:@"openVideo" handler:^(id data, GCWVJSBResponseCallback responseCallback) {

        [self getVideoList];
    }];
    
    /* JS调用OC的微信支付 */
    [_bridge registerObjCHandler:@"showSheet" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        NSLog(@"微信支付参数js调用oc传入的参数%@", data);
        AppDelegate * application = [[AppDelegate alloc]init];
        application.payType = 1;
        
        NSDictionary *dic =data;
        NSString *orderId =dic[@"orderId"];
        
        [self getWXOrderDetailDataWithOrderId:orderId];
    
    }];
    
    
    /*  JS 调用支付宝支付*/
    [_bridge registerObjCHandler:@"Alipay" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
//        if (responseCallback) {
//            // 反馈给JS
//            responseCallback(@{@"code": @"1",@"message": @"支付宝支付 "});
//        }
        AppDelegate * application = [[AppDelegate alloc]init];
        application.payType =2;
        
        
        NSDictionary *dic =data;
        NSString *orderId =dic[@"orderId"];
        [self getOrderDetailDataWithOrderId:orderId];
        
    }];
    
    
    /*  JS 调用微信授权登录*/
    [_bridge registerObjCHandler:@"WXLogin" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        
        [WXAUTH sendWXAuthReq];
        [WXAuth sharedInstance].delegate =self;
    }];
    
    
    /*  JS 调用微信语音识别*/
    [_bridge registerObjCHandler:@"WXVoice" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        //        if (responseCallback) {
        //            // 反馈给JS
        //            responseCallback(@{@"code": @"1",@"message": @"支付宝支付 "});
        //        }
        

        
        [[WXSpeech sharedInstance] addSpeechRecognizerView:self];
        
//        WXSpeechRecognizerViewController *view =[[WXSpeechRecognizerViewController alloc]init];
//        [self presentViewController:view animated:YES completion:nil];
        
    }];
    
//    [self renderButtons:self.webView];
    
    
    
    ///微信支付
    [WXApiManager sharedManager].delegate = self;

}

/////访问图片列表
-(void)getPicImageList{
    
    
    //        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //            if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    //                [self.view showImageHUDText:@"此设备不支持相机!"];
    //                return;
    //            }
    //            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    //            if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
    //
    //                UIAlertController *actionAlert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在设置-隐私-相机中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
    //                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //
    //                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    //                }];
    //                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    //                    NSLog(@"点击了取消");
    //                }];
    //
    //                [actionAlert addAction:action1];
    //                [actionAlert addAction:action2];
    //                [self presentViewController:actionAlert animated:YES completion:nil];
    //                return;
    //            }
    //            //        [self hx_presentCustomCameraViewControllerWithManager:self.manager delegate:self];
    //            __weak typeof(self) weakSelf = self;
    //            [self hx_presentCustomCameraViewControllerWithManager:self.manager done:^(HXPhotoModel *model, HXCustomCameraViewController *viewController) {
    //                [weakSelf.manager afterListAddCameraTakePicturesModel:model];
    //
    //            } cancel:^(HXCustomCameraViewController *viewController) {
    //                NSSLog(@"取消了");
    //            }];
    //
    //        }];
    //        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
    [self.manager clearSelectedList];///清空之前的选择
    [self hx_presentAlbumListViewControllerWithManager:self.manager delegate:self];
    
    //        }];
    //        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    //            NSLog(@"点击了取消");
    //        }];
    //        [actionSheet addAction:action1];
    //        [actionSheet addAction:action2];
    //        [actionSheet addAction:action3];
    //        [self presentViewController:actionSheet animated:YES completion:nil];
    
    
}
///访问本地视频
-(void)getVideoList{
    
    //        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"录制" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    //            //检测是否开通权限
    //            if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
    //
    //                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"暂无拍摄视频权限" preferredStyle:UIAlertControllerStyleAlert];
    //                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    //                [alert addAction:cancel];
    //                [self presentViewController:alert animated:YES completion:nil];
    //                return;
    //            }
    //            //使用UIImagePickerController视频录制
    //            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //            picker.delegate = self;
    //            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    //                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //            }
    //
    //            //mediaTypes设置摄影还是拍照
    //            //kUTTypeImage 对应拍照
    //            //kUTTypeMovie  对应摄像
    //            //    NSString *requiredMediaType = ( NSString *)kUTTypeImage;
    //            NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
    //            NSArray *arrMediaTypes=[NSArray arrayWithObjects:requiredMediaType1,nil];
    //            picker.mediaTypes = arrMediaTypes;
    //            //    picker.videoQuality = UIImagePickerControllerQualityTypeHigh;默认是中等
    //            picker.videoMaximumDuration = 60.; //60秒
    //            [self presentViewController:picker animated:YES completion:^{
    //
    //            }];
    //        }];
    //        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    //    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    //    if (availableMedia.count) {
    //        ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    //    }
    ipc.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
    
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
    //        }];
    //        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    //            NSLog(@"点击了取消");
    //            }];
    //            [actionSheet addAction:action1];
    //            [actionSheet addAction:action2];
    //            [actionSheet addAction:action3];
    //            [self presentViewController:actionSheet animated:YES completion:nil];
    
    
}
#pragma mark -
#pragma mark   ==============点击订单模拟支付行为==============
//
// 选中商品调用支付宝极简支付
//

-(void)getOrderDetailDataWithOrderId:(NSString*)orderId{
    
    [Utils POSTApliy:Url_W_AliPay_appPay parameters:@{@"orderId":orderId} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
       
    } success:^(id responseObject) {
        if (responseObject) {
            NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            NSString *payString = [[NSString alloc] initWithData:responseObject encoding:gbkEncoding];
            //version为@"\"xxx\"" ,在将字符串中\"替换为空即可
            payString = [payString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
         
            [self doAPPay:payString];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    

}
//微信获取订单详情
-(void)getWXOrderDetailDataWithOrderId:(NSString*)orderId{
    
    [Utils POSTApliy:Url_WeChatPay parameters:@{@"orderId":orderId} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    } success:^(id responseObject) {
        if (responseObject) {
            
            NSDictionary * rootDic = [self returnDictionaryWithDataPath:responseObject];
            WxPayModel * model = [[WxPayModel alloc]init];
            model.appid = [rootDic objectForKey:@"appid"];
            model.noncestr = [rootDic objectForKey:@"noncestr"];
            model.package = [rootDic objectForKey:@"package"];
            model.partnerid = [rootDic objectForKey:@"partnerid"];
            model.prepayid = [rootDic objectForKey:@"prepayid"];
            model.sign = [rootDic objectForKey:@"sign"];
            model.timestamp = [rootDic objectForKey:@"timestamp"];
            
            
            [WXApiRequestHandler jumpToBizPay:model];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
}
-(NSDictionary*)returnDictionaryWithDataPath:(NSData*)data
{
    NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSData * datas = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:datas options:NSJSONReadingMutableLeaves error:nil];
    
    return jsonDict;
}
- (void)doAPPay:(NSString *)payString
{

    // NOTE: 如果加签成功，则继续执行支付
    if (payString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"youyikuproject";
        NSLog(@"1111%lu",(unsigned long)payString.length);
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:payString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }
}
- (void)renderButtons:(UIWebView*)webView {
    
    
    self.msgLabel= [[UILabel alloc]initWithFrame:CGRectMake(30, 440, CGRectGetWidth(self.view.frame)-60, 40)];
    _msgLabel.numberOfLines =0;
    _msgLabel.backgroundColor =[UIColor orangeColor];
    [self.view insertSubview:self.msgLabel aboveSubview:webView];
    
    
    self.imageView =[[UIImageView alloc]initWithFrame:CGRectMake(80, CGRectGetMaxY(_msgLabel.frame)+30, 40, 60)];
    self.imageView.backgroundColor =[UIColor clearColor];
    [self.view insertSubview:self.imageView aboveSubview:webView];


    
    
    UIButton *getInfoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    getInfoBtn.backgroundColor = [UIColor orangeColor];
    getInfoBtn.layer.cornerRadius =6;
    getInfoBtn.layer.masksToBounds =YES;
    [getInfoBtn setTitle:@"getUserInfo" forState:UIControlStateNormal];
    [getInfoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [getInfoBtn addTarget:self action:@selector(getUserInfo) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:getInfoBtn aboveSubview:webView];
    getInfoBtn.frame = CGRectMake(10, CGRectGetMaxY(_imageView.frame)+20, 160, 35);
    
    UIButton *callAlertBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    callAlertBtn.backgroundColor = [UIColor orangeColor];
    callAlertBtn.layer.cornerRadius =6;
    callAlertBtn.layer.masksToBounds =YES;
    [callAlertBtn setTitle:@"alertMessage" forState:UIControlStateNormal];
    [callAlertBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [callAlertBtn addTarget:self action:@selector(alertMessage) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:callAlertBtn aboveSubview:webView];
    callAlertBtn.frame = CGRectMake(180, CGRectGetMaxY(_imageView.frame)+20, 160, 35);
}

- (void)getUserInfo {
    // 调用JS中的API
    [self.bridge callHandler:@"getUserInfo" data:@{@"userId":@"DX001"} responseCallback:^(id responseData) {
        NSString *userInfo = [NSString stringWithFormat:@"%@,姓名:%@,年龄:%@", responseData[@"userID"], responseData[@"userName"], responseData[@"age"]];
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"从网页端获取的用户信息" message:userInfo preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [vc addAction:cancelAction];
        [vc addAction:okAction];
        [self presentViewController:vc animated:YES completion:nil];
    }];
}

- (void)alertMessage {
    // 调用JS中的API
    [self.bridge callHandler:@"alertMessage" data:@"调用了js中的Alert弹窗!" responseCallback:^(id responseData) {
    }];
}

#pragma mark--UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"webViewDidStartLoad");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"webViewDidFinishLoad");
}


#pragma mark-HXCustomCameraViewControllerDelegate,HXAlbumListViewControllerDelegate

- (void)customCameraViewController:(HXCustomCameraViewController *)viewController didDone:(HXPhotoModel *)model {
    //    [self.manager afterListAddCameraTakePicturesModel:model];
    if (model.subType ==HXPhotoModelMediaSubTypePhoto) {//图片
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];

        ///上传图片
        [self uploadImage:model.previewPhoto imageTime:[dateFormatter stringFromDate:model.creationDate]];
        
    }else{//视频
        NSURL *source = model.videoURL;
        //计算视频大小
        CGFloat length = [self getVideoLength:source];
        CGFloat size = [self getFileSize:[source path]];
        NSLog(@"视频的时长为%lf s \n 视频的大小为%.2f M",length,size);
        //        压缩
        [self compressVideo:source];


    }
    
  
}

- (void)albumListViewController:(HXAlbumListViewController *)albumListViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original {
    NSSLog(@"%@",allList);
    NSSLog(@"%@",photoList);
    NSSLog(@"%@",videoList);

    if (photoList.count > 0) {
        
//        HXPhotoModel *model2 = photoList.firstObject;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        NSArray *newImageArr =[self sortedArrayUsingComparatorByPaymentTimeWithDataArr:photoList];
        
        ///上传图片
        for (HXPhotoModel*model in newImageArr) {
            NSLog(@"图片时间==%@",[dateFormatter stringFromDate:model.creationDate]);
            [self uploadImage:model.thumbPhoto imageTime:[dateFormatter stringFromDate:model.creationDate]];
        }
        
        
    }else if (videoList.count > 0) {
        
        NSURL *source = videoList[0].fileURL;
        //计算视频大小
        CGFloat length = [self getVideoLength:source];
        CGFloat size = [self getFileSize:[source path]];
        NSLog(@"视频的时长为%lf s \n 视频的大小为%.2f M",length,size);
//        //        压缩
        [self compressVideo:source];

    }
}

#pragma mark--UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image) {
        //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        [picker dismissViewControllerAnimated:YES completion:nil];
        
    }else{
        //会以MOV格式存储在tmp目录下
        NSURL *source = [info objectForKey:UIImagePickerControllerMediaURL];
        //计算视频大小
        CGFloat length = [self getVideoLength:source];
        CGFloat size = [self getFileSize:[source path]];
        NSLog(@"视频的时长为%lf s \n 视频的大小为%.2f M",length,size);
        
        [picker dismissViewControllerAnimated:YES completion:nil];
        //        压缩
        [self compressVideo:source];
    }
}
/**
 获取文件大小
 
 @param path 路径
 @return M
 */
- (CGFloat)getFileSize:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}
/**
 获取视频时长
 
 @param url url
 @return s
 */
- (CGFloat)getVideoLength:(NSURL *)url{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:url];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}
/**
 视频压缩
 */
- (void)compressVideo:(NSURL *)url{
    
    NSURL *newVideoUrl ; //一般.mp4
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉，减少空间。
    
    [self convertVideoQuailtyWithInputURL:url outputURL:newVideoUrl completeHandler:nil];
    
}


/**
 压缩完成调用上传
 
 @param inputURL 输入url
 @param outputURL 输出url
 @param handler AVAssetExportSession转码
 */
- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                               outputURL:(NSURL*)outputURL
                         completeHandler:(void (^)(AVAssetExportSession*))handler
{
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:{
                 //                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                 
                 dispatch_async(dispatch_get_global_queue(0, 0), ^{
                     CGFloat length = [self getVideoLength:outputURL];
                     CGFloat size = [self getFileSize:[outputURL path]];
                     
                     dispatch_async(dispatch_get_main_queue(), ^{
                         self.msgLabel.text = [NSString stringWithFormat:@"%.2f s, 压缩后大小为：%.2f M",length,size];
                         NSLog(@"压缩后==%@",[NSString stringWithFormat:@"%.2f s, 压缩后大小为：%.2f M",length,size]);
                     });
                 });
                 
                 
                 __weak __typeof(self) weakSelf = self;
                 // Get center frame image asyncly
                 [self centerFrameImageWithVideoURL:outputURL completion:^(UIImage *image) {
                     weakSelf.imageView.image = image;
                 }];
                 
//                 self.finalURL = outputURL;
                 [self uploadVideo:outputURL];
             }
                 
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
         
     }];
    
}
#pragma mark--图片上传接口
- (void)uploadImage:(UIImage *)image imageTime:(NSString*)picTime{
    
    NSData *data = UIImageJPEGRepresentation(image, 0.1);
    
    NSString *encodedImageStr = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",[data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    
//    NSLog(@"encodedImageStr = %@",encodedImageStr);
    [Utils post:Url_AppUpload parameters:@{@"imgData":encodedImageStr,@"timestamp":picTime} success:^(NSInteger recode, id jsonObject) {
        
        NSString * filepath = [jsonObject objectForKey:@"filepath"];//服务器图片路径
        NSString * filethumbpath = [jsonObject objectForKey:@"filethumbpath"];//缩略图
        
        NSURL *filepath_url =[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",HOSTURL,filepath]];
        NSURL *Filethumbpath_url =[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",HOSTURL,filethumbpath]];
        self.imageView.image =nil;
        [self.imageView sd_setImageWithURL:filepath_url placeholderImage:nil];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
    
    
}
#pragma mark--视频上传接口
/**
 视频上传
 
 @param url url
 */
- (void)uploadVideo:(NSURL *)url{
    //    上传data
    
    NSData *data = [NSData dataWithContentsOfURL:url];

    
    [Utils POST:Url_AppUploadMv parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //上传的参数(上传图片，以文件流的格式)
        
        NSDateFormatter*formatter=[[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyy-MM-dd-HH:mm:ss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%@.mp4",str] mimeType:@"video/mp4"];
        
        
    } success:^(id responseObject) {
        if (responseObject) {
            
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == -1) {//视频保存成功
                
                NSString * path = [responseObject objectForKey:@"path"];//服务器视频路径
                NSURL *path_url =[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",HOSTURL,path]];
                NSLog(@"视频路径==%@",path_url);
                
            }else{
            }
            [Utils alertViewWithMessage:[responseObject objectForKey:@"myerror"]];
        }
        
    } failure:^(NSError *error) {
      
    }];
    
    
    //    上传成功可以选择删除
        [[NSFileManager defaultManager] removeItemAtPath:[url path] error:nil];
    
    
}
// 异步获取帧图片，可以一次获取多帧图片
- (void)centerFrameImageWithVideoURL:(NSURL *)videoURL completion:(void (^)(UIImage *image))completion {
    // AVAssetImageGenerator
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    
    // calculate the midpoint time of video
    Float64 duration = CMTimeGetSeconds([asset duration]);
    // 取某个帧的时间，参数一表示哪个时间（秒），参数二表示每秒多少帧
    // 通常来说，600是一个常用的公共参数，苹果有说明:
    // 24 frames per second (fps) for film, 30 fps for NTSC (used for TV in North America and
    // Japan), and 25 fps for PAL (used for TV in Europe).
    // Using a timescale of 600, you can exactly represent any number of frames in these systems
    CMTime midpoint = CMTimeMakeWithSeconds(duration / 2.0, 600);
    
    // 异步获取多帧图片
    NSValue *midTime = [NSValue valueWithCMTime:midpoint];
    [imageGenerator generateCGImagesAsynchronouslyForTimes:@[midTime] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        if (result == AVAssetImageGeneratorSucceeded && image != NULL) {
            UIImage *centerFrameImage = [[UIImage alloc] initWithCGImage:image];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(centerFrameImage);
                }
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(nil);
                }
            });
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSArray *)sortedArrayUsingComparatorByPaymentTimeWithDataArr:(NSArray *)dataArr{
    
    NSArray *sortArray = [dataArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        HXPhotoModel *model1 = obj1;
        HXPhotoModel *model2 = obj2;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"yyyy-MM-dd"];
        
        NSDate *date1= model1.creationDate;
        NSDate *date2= model2.creationDate;
        
        if (date1 == [date1 earlierDate: date2]) { //不使用intValue比较无效
            
            return NSOrderedDescending;//降序
            
        }else if (date1 == [date1 laterDate: date2]) {
            
            return NSOrderedAscending;//升序
            
        }else{
            return NSOrderedSame;//相等
        }
    }];
    return sortArray;
}



#pragma mark-WXAuthDelegate
-(void)wXAuth:(WXAuth *)wXAuth wXUserInfo:(NSDictionary *)info{
    
    NSLog(@"info=%@",info);
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
